import os
import django
import csv
import datetime
import zipfile
import sys
from xml.dom import minidom
from django.db.models import Q

pro_dir = os.getcwd()
sys.path.append(pro_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mitagger.settings")

from home.models import Tag, Image
from home.models import Ontology
from home.models import Annotations
from home.models import Recommendations
from home.models import ImageTag
from home.models import TagType


head_description = ['imageFileName', 'TagID', 'TagName', 'Tag_FullID', 'OntologyName', 'OntologyVirtualID']
head_keys = [
            'imageFileName',
            'tagID',
            'tagName',
            'tag_fullID',
            'ontologyName',
            'ontologyVirtualId',
]

def generateFileName(fileFormat):
    now = datetime.datetime.now()
    fileNameFormat = '%(year)i-%(month)i-%(day)i-%(hour)i-%(minute)i-%(second)i-all.%(extension)s'
    fileNameValue = {
                     'year' : now.year,
                     'month' : now.month,
                     'day' : now.day,
                     'hour' : now.hour,
                     'minute' : now.minute,
                     'second' : now.second,
                     'extension': fileFormat,
                     }
    baseURL = 'downloads/'
    return baseURL + (fileNameFormat % fileNameValue)

def saveAllTagsToCSV(image_list):
    #get csv writer
    filename = generateFileName('csv')
    csv_writer = csv.writer(open(filename, 'wb'), delimiter=',')

    #get tagged image list
    image_list = Image.objects.filter(file_name__in=image_list, is_tagged=True).values_list('id', flat=True)
    #writer header
    #csv_writer.writerow([i for i in getTagsForCurrentImage(image_list[0])[0]])
    csv_writer.writerow(head_keys)

    #get all the tags
    for imageID in image_list:
        print 'Processing image ' + str(imageID)
        tag_info_list = getTagsForCurrentImage(imageID)
        for tag_info in tag_info_list:
            row = list()
            for key in head_keys:
                row.append(tag_info[key])
            csv_writer.writerow(row)

    del csv_writer

def saveAllTagsToXML(image_list):
    #get tagged image list
    image_list = Image.objects.filter(file_name__in=image_list, is_tagged=True).values_list('id', flat=True)
    #get xml doc & create root element
    doc  = minidom.Document()
    root = doc.createElement('Data')

    #get all tags & add to xml doc
    for imageID in image_list:
        tag_info_list = getTagsForCurrentImage(imageID)
        for tag_info in tag_info_list:
            tagNode = doc.createElement('Tag')
            print "Write data for image:" + tag_info['imageFileName']
            for key in tag_info:
                infoNode = doc.createElement('%s' % key)
                dataNode = doc.createTextNode('%s' % tag_info[key])
                infoNode.appendChild(dataNode)
                tagNode.appendChild(infoNode)
            root.appendChild(tagNode)
    doc.appendChild(root)
    #get xml str
    xml_str = doc.toxml('utf-8')

    #write to file
    filename = generateFileName('xml')
    xmlFile = open(filename, 'w')
    xmlFile.write(xml_str)
    xmlFile.close()

    #package file
    packageFileName = generateFileName('zip')
    packageFile = zipfile.ZipFile(packageFileName, mode='w', compression=zipfile.ZIP_STORED)
    packageFile.write(filename, getFileRelPath(filename))
    packageFile.close()
    os.remove(filename)

def getFileRelPath(fileName):
    dirName = os.path.dirname(fileName)
    relPath = os.path.relpath(fileName, dirName)
    
    return relPath

def getTagsForCurrentImage(figureID):
    tag_info_list   = list()
    tagIDList       = ImageTag.objects.filter(image_id=figureID, isSelected=True).values_list("tag_id", flat=True)
    #print "Selected tags: " + str(len(tagIDList))
    annotations     = Annotations.objects.filter(tag_id__in=tagIDList)
    recommendations = Recommendations.objects.filter(tag_id__in=tagIDList, image_id=figureID)
    imageFileName   = Image.objects.get(id=figureID).file_name
    recommendations = Recommendations.objects.filter(image_id=figureID, tag_id__in=tagIDList)
    #print "Recommendations tags: " + str(len(recommendations))
    for recommendation in recommendations:
        tagInfo = {
                    'imageFileName': imageFileName,
                    'tagID': recommendation.tag.id,
                    'tagName': recommendation.tag.name,
                    'tag_fullID': recommendation.tag.fullId,
                    'ontologyName':recommendation.tag.ontology.name,
                    'ontologyVirtualId': recommendation.tag.ontology.virtual_id,
        }
        tag_info_list.append(tagInfo)

    return tag_info_list; 

def form_tags(tag_list):
    res = []
    for tag in tag_list:
        tagInfo = {
                'imageFileName': tag.image.file_name,
                'tagID': tag.tag.id,
                'tagName': tag.tag.name,
                'tag_fullID': tag.tag.fullId,
                'ontologyName':tag.tag.ontology.name,
                'ontologyVirtualId': tag.tag.ontology.virtual_id,
        }
        res.append(tagInfo)
    return res

def save_user_tags_to_csv(username):
    #get csv writer
    filename = '%s.csv' % username
    csv_writer = csv.writer(open(filename, 'wb'), delimiter=',')

    #get tagged image list
    tag_id_list = ImageTag.objects.filter(author_id=username)
    #writer header
    #csv_writer.writerow([i for i in getTagsForCurrentImage(image_list[0])[0]])
    csv_writer.writerow(head_keys)
    res_list = form_tags(tag_id_list)
    for tag_info in res_list:
            row = list()
            for key in head_keys:
                row.extend(tag_info[key])
            csv_writer.writerow(row)

    #get all the tags
    del csv_writer

def save_user_tags_to_xml(username, image_list):
    #get csv writer
    doc  = minidom.Document()
    root = doc.createElement('Data')
    tag_id_list = ImageTag.objects.filter(author_id=username)
    res_list = form_tags(tag_id_list)
    for tag_info in res_list:
        tagNode = doc.createElement('Tag')
        print "Write data for image:" + tag_info['imageFileName']
        for key in tag_info:
            infoNode = doc.createElement('%s' % key)
            dataNode = doc.createTextNode('%s' % tag_info[key])
            infoNode.appendChild(dataNode)
            tagNode.appendChild(infoNode)
        root.appendChild(tagNode)
    doc.appendChild(root)

    filename = '%s.xml' % username
    xml_str = doc.toxml('utf-8')
    xmlFile = open(filename, 'w')
    xmlFile.write(xml_str)
    xmlFile.close()

    #package file
    packageFileName = '%s.zip' % username
    packageFile = zipfile.ZipFile(packageFileName, mode='w', compression=zipfile.ZIP_STORED)
    packageFile.write(filename, getFileRelPath(filename))
    packageFile.close()
    os.remove(filename)

def get_images():
    info_file = open('no_tags.txt', 'r')
    res = list()
    for line in info_file:
        if line.endswith('\n'):
            line = line[:-1]
        res.append(line)
    return res

def mainFunc():
    image_list = get_images();
    saveAllTagsToCSV(image_list)
    saveAllTagsToXML(image_list)
   #testAfter1990()

if __name__ == '__main__':
    django.setup()
    save_user_tags_to_csv('dinghuitong')